// 导入React核心功能
import React, { useState, useEffect, useRef } from 'react';
// 导入路由导航功能
import { useNavigate } from 'react-router-dom';
// 导入二维码生成组件
import { QRCodeSVG } from 'qrcode.react';
// 导入微信登录相关服务
import { 
  generateWechatQRCode, 
  checkWechatLoginStatus, 
  WechatLoginStatus, 
  type WechatLoginResult 
} from '../../services/wechatLogin';
// 导入认证上下文
import { useAuth } from '../../hooks/useAuth';
// 导入用户信息和角色类型
import { type UserInfo, UserRole } from '../../types/auth';
// 导入手机登录相关服务
import { phoneLogin, validatePhone, validatePassword } from '../../services/authService';
import './Login.css';

/**
 * 创作内容卡片接口
 * 定义展示在登录页面左侧的创意设计卡片
 */
interface CreativeCard {
  title: string;           // 卡片标题
  badge?: string;          // 可选徽章标签
  image: string;           // 卡片背景图片URL
  type: 'featured' | 'normal';  // 卡片类型：特色卡片或普通卡片
}

function Index() {
  // ===== 路由和认证相关 =====
  // 路由导航函数
  const navigate = useNavigate();
  // 认证上下文，提供登录功能
  const { login } = useAuth();

  // ===== 表单状态管理 =====
  // 手机号输入值
  const [phone, setPhone] = useState('');
  // 密码输入值
  const [password, setPassword] = useState('');
  // 登录方式：密码登录 或 验证码登录
  const [loginMethod, setLoginMethod] = useState<'password' | 'code'>('password');

  // ===== 微信登录状态管理 =====
  // 是否显示微信二维码弹窗
  const [showWechatQR, setShowWechatQR] = useState(false);
  // 二维码状态：等待、已扫描、已确认、已过期、错误
  const [qrCodeStatus, setQrCodeStatus] = useState<WechatLoginStatus>(WechatLoginStatus.WAITING);
  // 二维码URL
  const [qrCodeUrl, setQrCodeUrl] = useState('');
  // 微信用户信息
  const [userInfo, setUserInfo] = useState<{
    openid: string;
    nickname: string;
    headimgurl: string;
    unionid?: string;
  } | null>(null);
  // 状态消息提示
  const [statusMessage, setStatusMessage] = useState('');

  // ===== DOM引用 =====
  // 二维码弹窗的DOM引用，用于点击外部关闭
  const qrCodeRef = useRef<HTMLDivElement>(null);
  // 状态检查定时器的引用
  const statusCheckInterval = useRef<number | null>(null);

  // ===== 预设数据 =====
  /**
   * 创作内容卡片数据
   * 展示在登录页面左侧的创意设计作品，用于品牌展示和用户吸引
   */
  const creativeCards: CreativeCard[] = [
    {
      title: '版权商用授权书',
      badge: '正版 商用',
      image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?auto=format&fit=crop&w=300&q=80',
      type: 'featured'
    },
    {
      title: '版权无忧',
      image: 'https://images.unsplash.com/photo-1557683316-973673baf926?auto=format&fit=crop&w=300&q=80',
      type: 'normal'
    },
    {
      title: '个人 成长',
      image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?auto=format&fit=crop&w=300&q=80',
      type: 'normal'
    },
    {
      title: '一句话 让夫妻两人 相敬如宾',
      image: 'https://images.unsplash.com/photo-1557683316-973673baf926?auto=format&fit=crop&w=300&q=80',
      type: 'normal'
    },
    {
      title: '你好 四月',
      image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?auto=format&fit=crop&w=300&q=80',
      type: 'normal'
    },
    {
      title: '创新求变 赋能助力',
      image: 'https://images.unsplash.com/photo-1557683316-973673baf926?auto=format&fit=crop&w=300&q=80',
      type: 'normal'
    },
    {
      title: '科技赋能 将至已至',
      image: 'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?auto=format&fit=crop&w=300&q=80',
      type: 'normal'
    }
  ];

  // ===== 微信登录相关函数 =====
  const generateWechatQR = async () => {
    try {
      setQrCodeStatus(WechatLoginStatus.WAITING);
      setStatusMessage('正在生成二维码...');
      const state = Date.now().toString();
      const authUrl = await generateWechatQRCode();
      setQrCodeUrl(authUrl);
      setStatusMessage('请使用微信扫描二维码登录');
      startStatusCheck(state);
    } catch (error) {
      console.error('生成二维码失败:', error);
      setQrCodeStatus(WechatLoginStatus.ERROR);
      setStatusMessage('生成二维码失败，请重试');
    }
  };

  const startStatusCheck = (state: string) => {
    if (statusCheckInterval.current) {
      clearInterval(statusCheckInterval.current);
    }
    statusCheckInterval.current = setInterval(async () => {
      try {
        const result: WechatLoginResult = await checkWechatLoginStatus(state);
        setQrCodeStatus(result.status);
        setStatusMessage(result.message);
        if (result.status === WechatLoginStatus.CONFIRMED) {
          if (result.userInfo) {
            setUserInfo(result.userInfo);
            const userInfoForAuth: UserInfo = {
              id: result.userInfo.openid,
              openid: result.userInfo.openid,
              nickname: result.userInfo.nickname,
              headimgurl: result.userInfo.headimgurl,
              role: UserRole.USER,
              permissions: [],
              unionid: result.userInfo.unionid,
              accessToken: result.accessToken
            };
            login(userInfoForAuth);
          }
          setStatusMessage('登录成功，正在跳转...');
          if (statusCheckInterval.current) {
            clearInterval(statusCheckInterval.current);
          }
          setTimeout(() => {
            navigate('/home', { replace: true });
          }, 1500);
        } else if (result.status === WechatLoginStatus.EXPIRED || result.status === WechatLoginStatus.ERROR) {
          if (statusCheckInterval.current) {
            clearInterval(statusCheckInterval.current);
          }
        }
      } catch (error) {
        console.error('检查登录状态失败:', error);
        setQrCodeStatus(WechatLoginStatus.ERROR);
        setStatusMessage('检查状态失败，请重试');
      }
    }, 3000);
  };

  const refreshQRCode = () => {
    setQrCodeStatus(WechatLoginStatus.WAITING);
    setStatusMessage('正在刷新二维码...');
    generateWechatQR();
  };

  const handleWechatLogin = () => {
    setShowWechatQR(true);
    setUserInfo(null);
    generateWechatQR();
  };

  const closeWechatLogin = () => {
    setShowWechatQR(false);
    setQrCodeStatus(WechatLoginStatus.WAITING);
    setStatusMessage('');
    setUserInfo(null);
    if (statusCheckInterval.current) {
      clearInterval(statusCheckInterval.current);
    }
  };

  // ===== 手机登录相关函数 =====
  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    if (!validatePhone(phone)) {
      alert('请输入正确的11位手机号格式（以1开头）');
      return;
    }
    if (!validatePassword(password)) {
      alert('密码长度至少6位');
      return;
    }
    try {
      const response = await phoneLogin(phone, password);
      if (response.success && response.userInfo) {
        login(response.userInfo);
        alert('登录成功，正在跳转到首页...');
        navigate('/home', { replace: true });
      } else {
        alert(response.message);
      }
    } catch (error) {
      console.error('登录失败:', error);
      alert('登录失败，请重试');
    }
  };

  // ===== 导航相关函数 =====
  const handleBackToHome = () => {
    navigate('/');
  };

  // ===== 副作用钩子 =====
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (qrCodeRef.current && !qrCodeRef.current.contains(event.target as Node)) {
        closeWechatLogin();
      }
    };
    if (showWechatQR) {
      document.addEventListener('mousedown', handleClickOutside);
    }
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [showWechatQR]);

  useEffect(() => {
    return () => {
      if (statusCheckInterval.current) {
        clearInterval(statusCheckInterval.current);
      }
    };
  }, []);

  // ===== 组件渲染 =====
  return (
    <div className="login-container">
      {/* 左侧创作内容展示区域 */}
      <div className="creative-section">
        {/* 品牌信息头部 */}
        <div className="creative-header">
          <h1 className="brand-name">GAODING</h1>
          <p className="brand-slogan">创意设计，无限可能</p>
        </div>
        {/* 创作内容卡片网格 */}
        <div className="creative-cards">
          {creativeCards.map((card, index) => (
            <div key={index} className={`creative-card ${card.type}`}>
              <div className="card-image">
                <img src={card.image} alt={card.title} />
                {card.badge && (
                  <div className="card-badge">{card.badge}</div>
                )}
              </div>
              <div className="card-title">{card.title}</div>
            </div>
          ))}
        </div>
        {/* 版权信息底部 */}
        <div className="creative-footer">
          <div className="copyright-info">
            <h3>正版商用,版权无忧</h3>
            <p>内容正版商用保障,侵权问题从源头拦截 提供版权商用授权书,营销推广放心使用</p>
          </div>
        </div>
      </div>
      {/* 右侧登录表单区域 */}
      <div className="login-section">
        {/* 登录页面头部 */}
        <div className="login-header">
          <button className="back-btn" onClick={handleBackToHome}>
            ← 返回首页
          </button>
          <div className="wechat-login" onClick={handleWechatLogin}>
            <span>微信扫码登录</span>
            <div className="qr-code-icon">📱</div>
          </div>
        </div>
        {/* 登录表单主体 */}
        <div className="login-form">
          <h2 className="login-title">
            {loginMethod === 'password' ? '手机密码登录' : '手机验证码登录'}
          </h2>
          <form onSubmit={handleLogin}>
            {/* 手机号输入组 */}
            <div className="input-group">
              <div className="phone-input">
                <select className="country-code">
                  <option value="+86">+86</option>
                  <option value="+1">+1</option>
                  <option value="+44">+44</option>
                </select>
                <input
                  type="tel"
                  placeholder="输入11位手机号码"
                  value={phone}
                  onChange={(e) => setPhone(e.target.value)}
                  className="phone-field"
                  maxLength={11}
                  pattern="[0-9]{11}"
                />
              </div>
            </div>
            {/* 密码/验证码输入组 */}
            <div className="input-group">
              {loginMethod === 'password' ? (
                <input
                  type="password"
                  placeholder="输入6-30位密码"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  className="password-field"
                />
              ) : (
                <div className="code-input">
                  <input
                    type="text"
                    placeholder="输入验证码"
                    className="code-field"
                  />
                  <button type="button" className="send-code-btn">
                    发送验证码
                  </button>
                </div>
              )}
            </div>
            {/* 登录按钮 */}
            <button type="submit" className="login-btn">
              登录
            </button>
            {/* 测试账号提示 */}
            <div className="login-tips">
              <p><strong>测试账号：</strong></p>
              <p>管理员：11111111111 / admin123</p>
              <p>12222222222 / user123</p>
              <p><small>注意：手机号必须是11位数字</small></p>
            </div>
          </form>
          {/* 登录选项 */}
          <div className="login-options">
            <button 
              className="switch-login-btn"
              onClick={() => setLoginMethod(loginMethod === 'password' ? 'code' : 'password')}
            >
              {loginMethod === 'password' ? '手机验证码登录' : '手机密码登录'}
            </button>
            <button className="forgot-password-btn">
              忘记密码
            </button>
          </div>
          {/* 其他登录方式 */}
          <div className="other-login">
            <h4>其他方式登录</h4>
            <div className="login-methods">
              <button className="method-btn wechat" onClick={handleWechatLogin}>
                <span>💬</span>
                微信
              </button>
              <button className="method-btn qq" onClick={() => alert('QQ登录功能开发中...')}>
                <span>🐧</span>
                QQ
              </button>
              <button className="method-btn email" onClick={() => alert('邮箱登录功能开发中...')}>
                <span>📧</span>
                邮箱
              </button>
              <button className="method-btn more" onClick={() => alert('更多登录方式开发中...')}>
                <span>⋯</span>
                更多
              </button>
            </div>
          </div>
          {/* 登录页面底部 */}
          <div className="login-footer">
            <div className="agreement-text">
              注册登录即代表同意
              <a href="#" className="agreement-link">用户服务协议</a>、
              <a href="#" className="agreement-link">隐私政策</a>、
              <a href="#" className="agreement-link">会员服务协议</a>、
              <a href="#" className="agreement-link">授权许可协议</a>、
              <a href="#" className="agreement-link">产品联合运营协议</a>
            </div>
            <button className="register-btn">
              手机号注册
            </button>
          </div>
        </div>
      </div>
      {/* 微信扫码登录弹窗 */}
      {showWechatQR && (
        <div className="wechat-qr-modal">
          <div className="qr-modal-content" ref={qrCodeRef}>
            {/* 弹窗头部 */}
            <div className="qr-modal-header">
              <h3>微信扫码登录</h3>
              <button className="close-qr-btn" onClick={closeWechatLogin}>
                ✕
              </button>
            </div>
            {/* 二维码显示区域 */}
            <div className="qr-code-container">
              {qrCodeUrl ? (
                <QRCodeSVG value={qrCodeUrl} size={200} />
              ) : (
                <div className="qr-loading">
                  <div className="loading-spinner"></div>
                  <p>{statusMessage || '正在生成二维码...'}</p>
                </div>
              )}
              {/* 状态消息显示区域 */}
              <div className="qr-status">
                {qrCodeStatus === WechatLoginStatus.WAITING && (
                  <div className="status-message">
                    <p>{statusMessage || '请使用微信扫描二维码登录'}</p>
                    <p className="status-tip">二维码有效期为5分钟</p>
                  </div>
                )}
                {qrCodeStatus === WechatLoginStatus.SCANNED && (
                  <div className="status-message scanned">
                    <p>✅ 已扫描，请在手机上确认登录</p>
                  </div>
                )}
                {qrCodeStatus === WechatLoginStatus.CONFIRMED && (
                  <div className="status-message confirmed">
                    <p>✅ 登录成功，正在跳转...</p>
                    {userInfo && (
                      <div className="user-info">
                        <img src={userInfo.headimgurl} alt="头像" className="user-avatar" />
                        <p className="user-name">欢迎，{userInfo.nickname}</p>
                      </div>
                    )}
                  </div>
                )}
                {qrCodeStatus === WechatLoginStatus.EXPIRED && (
                  <div className="status-message expired">
                    <p>❌ 二维码已过期</p>
                    <button className="refresh-qr-btn" onClick={refreshQRCode}>
                      刷新二维码
                    </button>
                  </div>
                )}
                {qrCodeStatus === WechatLoginStatus.ERROR && (
                  <div className="status-message error">
                    <p>{statusMessage || '二维码生成失败，请重试'}</p>
                    <button className="refresh-qr-btn" onClick={refreshQRCode}>
                      刷新二维码
                    </button>
                  </div>
                )}
              </div>
            </div>
            {/* 弹窗底部提示 */}
            <div className="qr-modal-footer">
              <p>请使用微信扫描二维码完成登录</p>
              <p className="qr-tip">确保微信已安装并已登录</p>
            </div>
          </div>
        </div>
      )}
    </div>
  );
}

export default Index;
